/*
https://leetcode-cn.com/problems/data-stream-as-disjoint-intervals/solution/jiang-shu-ju-liu-bian-wei-duo-ge-bu-xian-hm1r/
 */

import java.util.Map;
import java.util.TreeMap;

public class Solution352 {

    TreeMap<Integer,Integer> map=new TreeMap<>();

    public Solution352() {

    }

    public void addNum(int val) {
        Map.Entry<Integer,Integer> e1=map.ceilingEntry(val+1);
        Map.Entry<Integer,Integer> e2=map.floorEntry(val);
        if (e2!=null && e2.getKey()<=val && e2.getValue()>=val){
            return;
        }
        boolean left=(e2!=null && e2.getValue()+1==val);
        boolean right=(e1!=null && e1.getKey()-1==val);
        if (left&&right){
            map.remove(e1.getKey());
            map.remove(e2.getKey());
            map.put(e2.getKey(),e1.getValue());
        }else if (left){
            map.put(e2.getKey(),e2.getValue()+1);
        }else if (right){
            map.put(e1.getKey()-1,e1.getValue());
            map.remove(e1.getKey());
        }else{
            map.put(val,val);
        }
    }

    public int[][] getIntervals() {
        int[][] ans=new int[map.size()][2];
        int t=0;
        for (Map.Entry<Integer,Integer> entry:map.entrySet()){
            ans[t][0]=entry.getKey();
            ans[t][1]=entry.getValue();
            t++;
        }
        return ans;
    }

    public static void main(String[] args) {
        Solution352 solution352=new Solution352();
        solution352.addNum(1);
        solution352.addNum(3);
        System.out.println(solution352.getIntervals().length);
        solution352.addNum(2);
        System.out.println(solution352.getIntervals().length);
    }
}
